
package cn.hpclub.server.service;

import cn.hpclub.server.util.excel.ExportUtils;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @FileName: CmccOrderGcgmService.java
 * @Author zhl
 * @Description:
 * @Date 2016年6月27日 下午2:38:57
 * @CopyRight ZTE Corporation
 */
public class TransactionLogService {

    private static final Logger    logger  = LoggerFactory.getLogger(TransactionLogService.class);
    public static TransactionLogService service = new TransactionLogService();

    public String getSqlExceptSelect(ConcurrentHashMap<String, String> searchInfo){
        String sqlExceptSelect = " from statistic_transaction t where 1=1  ";
        for(Entry<String, String> item : searchInfo.entrySet()){
            sqlExceptSelect += buildQuery(item);
        }
        sqlExceptSelect += " order by t.percent desc,t.api asc ";
        return sqlExceptSelect;
    }

    private String buildQuery(Entry<String, String> item){
        if("opt_time".equalsIgnoreCase(item.getKey())){
            String opt_start_time = "'" + item.getValue().replaceAll(" ", "") + " 00:00:00'";
            String opt_end_time = "'" + item.getValue().replaceAll(" ", "") + " 23:59:59'";
            return " and t.opt_time >= " + opt_start_time + " AND t.opt_time <="+opt_end_time;
        }
        if("singleApi".equalsIgnoreCase(item.getKey())){
            return "";
        }
        return " and t." + item.getKey() + " = '" + item.getValue() + "'";
    }

    private String buildQueryForSingle(Entry<String, String> item){
        if("opt_time".equalsIgnoreCase(item.getKey())){
            String opt_start_time = "'" + item.getValue().replaceAll(" ", "") + " 00:00:00'";
            String opt_end_time = "'" + item.getValue().replaceAll(" ", "") + " 23:59:59'";
            return " and t.opt_time >= " + opt_start_time + " AND t.opt_time <="+opt_end_time;
        }
        if("singleApi".equalsIgnoreCase(item.getKey())){
            return " and t.api = '" + item.getValue() + "'";
        }
        return " and t." + item.getKey() + " = '" + item.getValue() + "'";
    }





    /**
     * @describe
     * @param searchInfo
     *            查询条件参数列表
     * @return SXSSFWorkbook
     */
    public SXSSFWorkbook getExcel(ConcurrentHashMap<String, String> searchInfo){
        SXSSFWorkbook workbook = null;
        String sql = " SELECT *   " + getSqlExceptSelect(searchInfo);

        List<Record> seq = Db.find(sql);
        for (Record record : seq) {
            record.set("percent",record.getDouble("percent") + "%");
        }
        String[] excelHeaders = new String[] { "接口描述","接口名", "总共调用次数", "成功笔数", "失败笔数", "失败率" };
        ExportUtils exportUtils = new ExportUtils(excelHeaders);
        String[] keys = new String[] { "describes","api", "total", "success", "failed", "percent" };
        try{
            exportUtils.exportExcel(keys, seq, "yyyy-MM-dd HH:ss:mm", 1);// 此处最后一个参数表示从第一行开始填入数据（表头为第0行）
            workbook = exportUtils.getSXSSFWorkbook();
        }
        catch(FileNotFoundException e){
            logger.error("TransactionLogService.getExcel(ConcurrentHashMap<String, String> searchInfo) happened an FileNotFoundException,error message:"
                    + e.getMessage());
        }
        catch(IOException ex){
            logger.error("TransactionLogService.getExcel(ConcurrentHashMap<String, String> searchInfo) happened an IOException,error message:"
                    + ex.getMessage());
        }
        return workbook;
    }



    /**
     * @describe
     * @param searchInfo
     *            查询条件参数列表
     * @return SXSSFWorkbook
     */
    public SXSSFWorkbook getOneApiExcel(ConcurrentHashMap<String, String> searchInfo){
        SXSSFWorkbook workbook = null;
        String sql = " SELECT * FROM transaction_log t WHERE t.success!=1  ";
        for(Entry<String, String> item : searchInfo.entrySet()){
            sql += buildQueryForSingle(item);
        }
        sql += " order by t.opt_time desc  ";
        List<Record> seq = Db.find(sql);
        seq.stream().forEach(record->{
            if(StrKit.isBlank(record.getStr("boss_output"))){
                record.set("boss_output",record.getStr("client_output"));
            }
        });
        String[] excelHeaders = new String[] { "客户端入参","BOSS入参", "接口名", "错误原因", "接口报错时间" };
        ExportUtils exportUtils = new ExportUtils(excelHeaders);
        String[] keys = new String[] { "client_input","boss_input", "api", "boss_output", "opt_time" };
        try{
            exportUtils.exportExcel(keys, seq, "yyyy-MM-dd HH:ss:mm", 1);
            workbook = exportUtils.getSXSSFWorkbook();
        }
        catch(FileNotFoundException e){
            logger.error("TransactionLogService.getOneApiExcel(ConcurrentHashMap<String, String> searchInfo) happened an FileNotFoundException,error message:"
                    + e.getMessage());
        }
        catch(IOException ex){
            logger.error("TransactionLogService.getOneApiExcel(ConcurrentHashMap<String, String> searchInfo) happened an IOException,error message:"
                    + ex.getMessage());
        }
        return workbook;
    }


    public String getApiDescribeSqlExceptSelect(ConcurrentHashMap<String, String> searchInfo){
        String sqlExceptSelect = " from api_describe a where 1=1  ";
        for(Entry<String, String> item : searchInfo.entrySet()){
            sqlExceptSelect += buildApiDescribeQuery(item);
        }
        sqlExceptSelect += " order by a.api asc ";
        return sqlExceptSelect;
    }

    private String buildApiDescribeQuery(Entry<String, String> item){
        return " and a." + item.getKey() + " like '%" + item.getValue().trim() + "%'";
    }



    public boolean getTariffByCityAndCode(String api,int id){
       String sql = "select * from api_describe where api= '"+api.trim()+"'";
       List<Record> list = Db.find(sql.toString());
       if(id == 0){
           return list.size() > 0 ? true : false;
       }else{
           if(list.size()==0){
               return false;
           }else if(list.size() > 1 ){
               return true;
           }else{
               Record record = list.get(0);
               int resultId = record.getInt("id");
               if(resultId != id){
                   return true;
               }else{
                   return false;
               }
           }
       }
    }

}
